#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <cerrno>
// const std::string path = "./wwwroot/test1.html";
// // const std::string root_path = "/home/xuqin/linux-learning/lesson/lesson47/wwwroot";
const std::string root_path = "./wwwroot";

namespace Util
{
    static void ReadFile(std::string request, std::string *file_content)
    {
        // 解析出客户端请求方式
        // std::string method = request.substr(0, request.find(" "));
        // 解析出请求文件路径    方法1
        // int pos_s = request.find(" ") + 1;
        // std::string a(request.begin() + pos_s, request.end());
        // int pos_e = a.find(" ");
        // std::string path = root_path + std::string(request.begin() + pos_s, request.begin() + pos_e + pos_s);

        // 解析出请求文件路径   方法2
        std::string first_line(request.begin(), request.begin() + request.find("\r\n"));
        std::stringstream ss(first_line);
        std::string path, a, b, c;
        ss >> a >> b >> c;
        path = root_path + b;

        // std::cout << path << std::endl;

        // 获取文件大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if (n < 0)
        {
            path = root_path + "/404.html";
            stat(path.c_str(), &st);
        }
        int size = st.st_size;

        logMessage(Info, "path:%s", path.c_str());

        // 打开文件
        int fd = open(path.c_str(), O_RDONLY);
        if (fd < 0)
            logMessage(Fatal, "open file error, %d:%s", errno, strerror(errno));
        file_content->resize(size);
        read(fd, (char *)file_content->c_str(), size);

        close(fd);
    }

} // namespace Util
